//mainwindow.cpp
#include "mainwindow.h"
#include "ui_mainwindow.h"
MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    socket = new QTcpSocket();          //实例化tcp客户端
    ti = new QTimer();                  //定时器
    sizz = 0;
    sizz2 = 0;
    //连接信号槽
    QObject::connect(socket, &QTcpSocket::readyRead, this, &MainWindow::socket_Read_Data);
    ui->lineEdit_IP->setText("192.168.4.1");        //ip地址
    ui->lineEdit_Port->setText("8080");         //端口号

    connect(ti , SIGNAL(timeout()) , this , SLOT(timeshow()));
    ti->start(1000);
    initChart();
    initChart_openfile();
}
void MainWindow::timeshow()         //发送时间到单片机
{
    tim = QDateTime::currentDateTime();
    ui->dateTimeEdit->setDateTime(tim);
}
void MainWindow::initfile()                     //初始化文件
{
    bool res;
    QString tim1 = tim.toString("yyyy-MM-dd-hh-mm-ss");
    QString nameph = tim1 + "-ph.txt";
    QString nameph2 = tim1 + "-ph2.txt";
    QString nametm =tim1 + "-tm.txt";
    QString namehu =tim1 + "-hu.txt";
    fileph = new QFile();
    fileph->setFileName(nameph);
    res = fileph->open(QIODevice::ReadWrite|QIODevice::Text);       //打开文件
    qDebug()<<"ph------------------"<<res;
    fileph2 = new QFile();
    fileph2->setFileName(nameph2);
    res = fileph2->open(QIODevice::ReadWrite|QIODevice::Text);       //打开文件
    qDebug()<<"ph2------------------"<<res;
    filetm = new QFile;
    filetm->setFileName(nametm);
    res = filetm->open(QIODevice::ReadWrite|QIODevice::Text);
    qDebug()<<"tm------------------"<<res;
    filehumi = new QFile;
    filehumi->setFileName(namehu);
    res = filehumi->open(QIODevice::ReadWrite|QIODevice::Text);
    qDebug()<<"hu------------------"<<res;
    //out = new QTextStream(fileph);out1 = new QTextStream(filetm);out2 = new QTextStream(filehumi);
}

MainWindow::~MainWindow()
{
    delete this->socket;
    if(fileph->isOpen())
    {
        fileph->close();
    }
    if(filetm->isOpen())
    {
        filetm->close();
    }
    if(filehumi->isOpen())
    {
        filehumi->close();
    }
    if(fileph2->isOpen())
    {
        fileph2->close();
    }
    delete ui;
}

void MainWindow::on_pushButton_Connect_clicked()
{
    if(ui->pushButton_Connect->text() == tr("连接"))
    {
        QString IP;
        int port;

        //获取IP地址
        IP = ui->lineEdit_IP->text();
        //获取端口号
        port = ui->lineEdit_Port->text().toInt();

        //取消已有的连接
        socket->abort();
        //连接服务器
        socket->connectToHost(IP, port);

        //等待连接成功
        if(!socket->waitForConnected(30000))
        {
            qDebug() << "Connection failed!";
            return;
        }
        qDebug() << "Connect successfully!";
        //修改按键文字
        ui->pushButton_Connect->setText("断开连接");
        initfile();
    }
    else
    {
        //断开连接
        socket->disconnectFromHost();
        //修改按键文字
        ui->pushButton_Connect->setText("连接");
        fileph->close();
        fileph2->close();
        filetm->close();
        filehumi->close();
    }
}

void MainWindow::socket_Read_Data()
{
    QString recvdata = socket->readAll();
    qDebug() << recvdata;
    QString tm;int res = -1;
    if(recvdata.isEmpty() || recvdata.size()<4)
        return;
    else
    {
        if(recvdata[0] == '#')          //#ph *温湿度
            res = 0;
        else if(recvdata[0] == '*')
            res = 1;
        else if(recvdata[0] == 'G')
            res = 2;
    }
    if(res == 0)
    {
        QStringList list = recvdata.split('#');
        QString tmp = list[1];
        QString tmp_my;
        if(tmp.size() < 5)
            return;
        tmp_my.append(tmp[0]);
        tmp_my.append(tmp[1]);
        tmp_my.append(tmp[2]);
        tmp_my.append(tmp[3]);
        tmp_my.append(tmp[4]);
        ui->lineEdit->setText(tmp_my);
        phh = tmp_my;
        sizz++;
        if(sizz == 20)                  //20个字符之后将容器清空，容器存储太多会卡
        {
            sizz = 0;
            x.clear();
            y.clear();
            ui->widget->graph(0)->data().data()->clear();
            ui->widget->replot();
        }
        x.append(sizz);            //将获取到的时间进行格式整理并转换为double类型
        y.append(phh.toDouble());

        graph1->addData(x ,y);      //添加绘图的线
        ui->widget->setInteractions(QCP::iRangeDrag | QCP::iRangeZoom | QCP::iSelectPlottables);
        ui->widget->replot();

        fileph->write(phh.toStdString().c_str());
        fileph->write("\n");
        //*out << phh<<endl;

    }
    else if(res == 1)       //温湿度的时候
    {
        QStringList list = recvdata.split('*');
        qDebug()<<list;
        QString tmp = list[1];
        QStringList my_tmp = tmp.split(',');
        ui->lineEdit_2->setText(my_tmp[0]+"℃");
        QString tmp_my;
        tmp_my.append(my_tmp[1][0]);
        tmp_my.append(my_tmp[1][1]);
        ui->lineEdit_3->setText(tmp_my+"%");
        tmm = my_tmp[0];
        hii = tmp_my;
        sizz2++;
        if(sizz2 == 20)
        {
            x_tm.clear();
            y_tm.clear();
            x_hi.clear();
            y_hi.clear();
            sizz2 = 0;
            ui->widget->graph(1)->data().data()->clear();
            ui->widget->graph(2)->data().data()->clear();

            ui->widget->replot();
        }
        x_tm.append(sizz2);
        y_tm.append(tmm.toDouble());
        y_hi.append(hii.toDouble());
        graph2->addData(x_tm ,y_tm);
        graph3->addData(x_tm ,y_hi);
        //ui->widget->rescaleAxes();
        ui->widget->setInteractions(QCP::iRangeDrag | QCP::iRangeZoom | QCP::iSelectPlottables);
        ui->widget->replot();
        filetm->write(tmm.toStdString().c_str());
        filetm->write("\n");
        filehumi->write(hii.toStdString().c_str());
        filehumi->write("\n");
    }
    else if(res == 2)
    {
        QStringList list = recvdata.split('G');
        QString tmp = list[1];
        QString tmp_my;
        if(tmp.size() < 5)
            return;
        tmp_my.append(tmp[0]);
        tmp_my.append(tmp[1]);
        tmp_my.append(tmp[2]);
        tmp_my.append(tmp[3]);
        tmp_my.append(tmp[4]);
        ui->lineEdit_4->setText(tmp_my);
        phh2 = tmp_my;
        sizz3++;
        if(sizz3 == 20)                  //20个字符之后将容器清空，容器存储太多会卡
        {
            sizz3 = 0;
            x_2.clear();
            y_2.clear();
            ui->widget->graph(3)->data().data()->clear();
            ui->widget->replot();
        }
        x_2.append(sizz3);            //将获取到的时间进行格式整理并转换为double类型
        y_2.append(phh.toDouble());

        graph4->addData(x_2 ,y_2);      //添加绘图的线
        ui->widget->setInteractions(QCP::iRangeDrag | QCP::iRangeZoom | QCP::iSelectPlottables);
        ui->widget->replot();

        fileph2->write(phh2.toStdString().c_str());
        fileph2->write("\n");
        //*out << phh<<endl;

    }
}


void MainWindow::initChart_openfile()               //初始化打开文件的画板
{
    ui->widget_2->axisRect()->setBackground(QBrush(Qt::black));

    ui->widget_2->legend->setVisible(true);
    ui->widget_2->xAxis->setLabel("Time(s)");//设置ｘ轴
    ui->widget_2->xAxis->setTicks(true);

    ui->widget_2->yAxis->setLabel("%/℃");//设置ｙ轴
    ui->widget_2->yAxis->setTicks(true);


    graph_1 = ui->widget_2->addGraph();//增加一条曲线图层



    QCPScatterStyle QCPcs1(QCPScatterStyle::ssSquare, QColor(255,0,0),QColor(255,0,0),3);//设置折线图的点的形状及颜色
    QPen qPen1(QColor(255,0,0));
    graph_1->setScatterStyle(QCPcs1);
    graph_1->setPen(qPen1);//设置画笔颜色
    graph_1->setName(QString("data"));

    ui->widget_2->xAxis->ticker()->setTickCount(11);//11个主刻度
    ui->widget_2->xAxis->ticker()->setTickStepStrategy(QCPAxisTicker::tssReadability);


    ui->widget_2->yAxis->ticker()->setTickCount(11);

    ui->widget_2->yAxis->setRangeLower(0);
    ui->widget_2->xAxis->setRangeLower(0);
    ui->widget_2->xAxis->setRangeUpper(50);
    ui->widget_2->yAxis->setRangeUpper(100);
}


void MainWindow::initChart()            //初始化的实时检测
{
    ui->widget->axisRect()->setBackground(QBrush(Qt::black));

    ui->widget->legend->setVisible(true);
    ui->widget->xAxis->setLabel("Time(s)");//设置ｘ轴
    ui->widget->xAxis->setTicks(true);

    ui->widget->yAxis->setLabel("%/℃");//设置ｙ轴
    ui->widget->yAxis->setTicks(true);


    graph1 = ui->widget->addGraph();//增加一条曲线图层
    graph2 = ui->widget->addGraph();//增加一条曲线图层
    graph3 = ui->widget->addGraph();//增加一条曲线图层
    graph4 = ui->widget->addGraph();//增加一条曲线图层


    QCPScatterStyle QCPcs1(QCPScatterStyle::ssSquare, QColor(255,0,0),QColor(255,0,0),3);//设置折线图的点的形状及颜色
    QPen qPen1(QColor(255,0,0));
    graph1->setScatterStyle(QCPcs1);
    graph1->setPen(qPen1);//设置画笔颜色
    graph1->setName(QString("ph1"));


    QCPScatterStyle QCPcs4(QCPScatterStyle::ssCircle, QColor(0,255,0),QColor(0,255,0),3);//设置折线图的点的形状及颜色
    QPen qPen4(QColor(0,255,255));
    graph4->setScatterStyle(QCPcs4);
    graph4->setPen(qPen4);//设置画笔颜色
    graph4->setName(QString("ph2"));


    QCPScatterStyle QCPcs2(QCPScatterStyle::ssCircle, QColor(0,255,0),QColor(0,255,0),3);//设置折线图的点的形状及颜色
    QPen qPen2(QColor(0,255,0));
    graph2->setScatterStyle(QCPcs2);
    graph2->setPen(qPen2);//设置画笔颜色
    graph2->setName(QString("温度"));

    QPen qPen3(QColor(0,0,255));
    graph3->setScatterStyle(QCPcs2);
    graph3->setPen(qPen3);//设置画笔颜色
    graph3->setName(QString("湿度"));

    ui->widget->xAxis->ticker()->setTickCount(11);//11个主刻度
    ui->widget->xAxis->ticker()->setTickStepStrategy(QCPAxisTicker::tssReadability);
    ui->widget->yAxis->ticker()->setTickCount(11);

    ui->widget->yAxis->setRangeLower(0);
    ui->widget->xAxis->setRangeLower(0);
    ui->widget->xAxis->setRangeUpper(50);
    ui->widget->yAxis->setRangeUpper(100);
}


bool MainWindow::loadFile(const QString& filename) {        //选择文件
    read_ph.clear();
    QFile file(filename);
    if (!file.open(QFile::ReadOnly | QFile::Text)) {
        QMessageBox::warning(this, tr("多文档编辑器"), tr("无法读取文件: %1 \n %2").arg(filename).arg(file.errorString()));
        return false;
    }
    QTextStream in(&file);                          //构造一个指向file文件的QTextStream对象,输入数据流
    QApplication::setOverrideCursor(Qt::WaitCursor);//鼠标保持旋转状态
    //将文件内容读取出来,并写入在ui编辑器中.
    while(!in.atEnd())
    {
        read_ph.append(in.readLine().toDouble());
    }
    return true;
}

void MainWindow::on_pushButton_clicked()
{
    QString FileName = QFileDialog::getOpenFileName(this,tr("请选择需要打开的文件"),"","*.txt");
    if (!FileName.isEmpty()) {
        if(loadFile(FileName))
        {
            QVector<double>x_pp;
            for(int i = 0;i<read_ph.size();i++)
            {
                x_pp.append(i);
            }
            qDebug()<<read_ph;
            if(!read_ph.isEmpty())
            {
                graph_1->setData(x_pp,read_ph);
                ui->widget->setInteractions(QCP::iRangeDrag | QCP::iRangeZoom | QCP::iSelectPlottables);
                ui->widget_2->replot();
            }
        }
    }

}

void MainWindow::on_pushButton_2_clicked()
{
    QWidget *widget = new QWidget;
    QTextEdit *edit = new QTextEdit(widget);
    edit->setGeometry(widget->geometry());
    if(!read_ph.isEmpty())
    {
        for(auto i : read_ph)
        {
            edit->append(QString::number(i));
        }
        widget->show();
    }
}
